package com.elasticsearch.demo.security;

import com.elasticsearch.demo.model.entity.User;
import com.elasticsearch.demo.service.IUserService;
import com.elasticsearch.demo.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.DigestUtils;

/**
 * 自定义认证实现
 */
public class AuthProvider implements AuthenticationProvider {

    @Autowired
    private IUserService userService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String inputPassword = (String) authentication.getCredentials();

        User user = userService.findUserByName(name);

        //判断用户是否存在
        if (user == null) {
            throw new AuthenticationCredentialsNotFoundException("authError");
        }

        //使用security5 的BCrypt加密方式
        if (MD5Util.encryptPassword(inputPassword, user.getId().toString()).equals(user.getPassword())) {
            return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        }


        throw new BadCredentialsException("authError");
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
